package com.joelemon.mockinfluxdbdata.core.config;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.joelemon.mockinfluxdbdata.enums.CommonFlag;
import com.joelemon.mockinfluxdbdata.enums.RunningFlag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: mock任务
 * @Author: HJY
 * @Date: 2023/11/20
 */
@Service()
@Slf4j
@RequiredArgsConstructor
public class MockTaskService extends ServiceImpl<MockTaskMapper, MockTask> {

    public List<MockTask> prepareNewTasks() {
        // 查询任务
        List<MockTask> mockTasks = getTasks(RunningFlag.NO);
        if (mockTasks == null || mockTasks.size() == 0)return null;
        // 修改状态
        for (MockTask mockTask : mockTasks) {
            updateStatus(mockTask.getId(), RunningFlag.RUNNING);
        }
        // 返回任务
        return mockTasks;
    }

    public List<MockTask> getTasks(RunningFlag runningFlag) {
        return this.baseMapper.queryAllByStatus(runningFlag, CommonFlag.NO);
    }

    public MockTask getTask(Long id) {
        List<MockTask> list = this.lambdaQuery().eq(MockTask::getId, id).list();
        if (list == null || list.size()  == 0) return null;
        return list.get(0);
    }

    public void updateStatus(Long id, RunningFlag status) {
        this.lambdaUpdate().set(MockTask::getStatus, status).eq(MockTask::getId, id).update();
    }
}
